package com.reason.user.controller;

import com.reason.common.pojo.Result;
import com.reason.common.pojo.StatusCode;
import com.reason.user.config.TokenDecode;
import com.reason.user.dto.CustomerDTO;
import com.reason.user.pojo.Customer;
import com.reason.user.service.CustomerService;
import jdk.net.SocketFlow;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author  yulongjun
 * @date 2020/6/29 10:42 下午
 */
@RestController
@RequestMapping("/customer")
public class CustomerController {

    /**
     * customer的服务类
     */
    @Autowired
    private CustomerService customerService;

    /**
     * 注入解析令牌的类
     */
    @Autowired
    private TokenDecode tokenDecode;

    /**
     * 查询用户信息
     * @param username
     * @return
     */
    @RequestMapping("/find/{username}")
    public Customer findbyName(@PathVariable("username") String username) {

        try {

            Customer customer = customerService.findCustomer(username);
            System.out.println(customer);
            return customer;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 查询所有
     *
     * @return
     */
    @RequestMapping("/findAll")
    public  List<Customer> findAll() {

        List<Customer> brandList = customerService.findBrandList();
        System.out.println(brandList);
        return brandList;
    }

    /**
     * 根据ID查询Customer
     *
     * @param Id
     * @return
     */
    @GetMapping("/findById/{Id}")
    public Result<Customer> findById(@PathVariable("Id") Long Id) {
        Customer customer = customerService.findByID(Id);
        if (customer == null) {
            return new Result(false, StatusCode.ERROR, "该用户不存在");
        }
        return new Result(true, StatusCode.OK, "查询成功", customer);
    }

    /**
     * 根据id修改会员等级
     *
     * @param userId           用户id
     * @param membership_level 会员等级
     * @return
     */
    @RequestMapping("/update/member")
    public Result updateMember(@RequestParam String userId, @RequestParam String membership_level) {
        int i = customerService.updateMember(userId, membership_level);
        return new Result(true, StatusCode.OK, "修改成功", i);
    }

    /**
     * 获取令牌信息的方法
     */
    @RequestMapping("/test")
    public void Test() {
        Map<String, String> map = tokenDecode.getUserInfo();
        System.out.println(map);

    }

    /**
     * 根据电话号码获取用户信息
     */
    @RequestMapping("/findByTelephone/{telephone}")
    public Customer findByTelephone(@PathVariable("telephone") Long telephone) {
        try {
            Customer customer = customerService.findByTelephone(telephone);
            return customer;
        }catch (Exception e){
            e.printStackTrace();
            return null;

        }


    }

    /**
     * 注册用户成为一级用户（意思就是只是手机号登陆，其他信息都没有的状态）
     */
    @PostMapping("/register")
    public void register(@RequestBody Customer customer){
        if(customer!=null){
            customerService.register(customer);
            return;
        }
        System.out.println("注册一级会员信息为空");

    }

    /**
     * 注册成为二级会员(意思就是添加必须要填的资料)
     * @return
     */
    @RequestMapping("/registerSeniorMember")
    public Result<Customer> registerSeniorMember(@RequestBody Customer customer){
        if(customer!=null){
            //用户信息不为空
            boolean b = customerService.registerSeniorMember(customer);
            if(b){
                return new Result<Customer>(true,StatusCode.OK,"恭喜成为1级用户", 1);

            }else {
                return new Result<Customer>(false,StatusCode.ERROR,"信息不全或没有", 0);
            }
        }
        return new Result<Customer>(false,StatusCode.ERROR,"您输入的用户信息为空");

    }

    @PostMapping("/queryForCondition")
    public Result queryForCondition(@RequestBody Map<String,String> searchMap){
        Map<String,Object> data = customerService.queryForCondition(searchMap);
        return new Result(true, StatusCode.OK, "查询成功", data);
    }
    @GetMapping("/queryForById/{cusid}")
    public Result queryForById(@PathVariable("cusid") Long cusid, HttpServletRequest request){
        Map<String,Object> data=customerService.queryForById(cusid);
        String idStr = this.getCookie("id", request);
        if (StringUtils.isNotBlank(idStr)) {
            Long id = Long.valueOf(idStr);
            List<Customer> similarList = customerService.findSimilarList(id);
            data.put("similarList", similarList);
        }
        return new Result(true, StatusCode.OK, "查询成功", data);
    }
 /*   @GetMapping("/updateALl")
    public Result updateAll(@RequestBody ){

    }
*/

    @PostMapping("/updateDetail")
    public Result updateDetail(@RequestBody CustomerDTO customerDTO) {
        boolean flag = customerService.updateDetail(customerDTO);
        if (flag) {
            return new Result(false, StatusCode.ERROR, "个人信息修改失败");
        }
        return new Result(true, StatusCode.OK, "个人信息修改成功");
    }

    @GetMapping("/check")
    public Result check(HttpServletRequest request) {
        String id = this.getCookie("id", request);
        if (id == null) {
            return new Result(false, StatusCode.ERROR, "查询登录状态失败");
        }
        Customer customer = customerService.findByID(Long.valueOf(id));
        return new Result(true, StatusCode.OK, "查询登录状态成功", customer.getMember());
    }

    private String getCookie(String name, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies == null || cookies.length == 0) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie.getValue();
            }
        }
        return null;
    }

}



